<template>
  <div class="player" v-show="playlist.length > 0">
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="currentSong.image">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="mui-icon mui-icon-arrowdown mui-xiangxia"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle">
          <div class="middle-l">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img class="image" :src="currentSong.image">
              </div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine"
                  class="text"
                  :class="{'current': currentLineNum === index}"
                  v-for="(line, index) in currentLyric.lines"
                  :key="index"
                >
                  {{ line.txt }}
                </p>
              </div>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{format(duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i :class="iconMode"></i>
            </div>
            <div class="icon i-left">
              <i class="iconfont icon-xiangzuo" :class="disableCls" @click="prev"></i>
            </div>
            <div class="icon i-center" :class="disableCls">
              <i :class="playIcon" @click="togglePlaying"></i>
            </div>
            <div class="icon i-right" >
              <i class="iconfont icon-xiangyou" :class="disableCls" @click="next"></i>
            </div>
            <div class="icon i-right" @click.stop="showPlaylist">
              <i class="mui-icon mui-icon-list"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
        <div class="icon">
          <img width="40" height="40" :src="currentSong.image" :class="cdCls">
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control"></div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i @click.stop="togglePlaying" :class="miniIcon" class="icon-mini"></i>
          </progress-circle>
        </div>
        <div class="control">
          <i class="mui-icon mui-icon-settings icon-setting"></i>
        </div>
      </div>
    </transition>
    <play-list ref="playlist"></play-list>
    <audio ref="audio" autoplay @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
  </div>
</template>

<script type="text/javascript">
import { mapGetters, mapMutations } from 'vuex'
import animations from 'create-keyframe-animation'
// 获取当前音乐
import { getSong, getLyric } from '@/api/song'
// 获取进度条组件
import ProgressBar from '@/base/progress-bar/progress-bar'
// 获取缩小的进度条组件
import ProgressCircle from '@/base/progress-circle/progress-circle'
// 引入播放模式索引1 2 0
import { playMode } from '@/common/js/config'
// 打乱数组方法
import { shuffle } from '@/common/js/util'
// 引入模式图标方法
import { playerMixin } from '@/common/js/mixin'
// import { prefixStyle } from '@/common/js/dom'
// 处理歌词
import Lyric from 'lyric-parser'
import Scroll from '@/base/scroll/scroll'
import PlayList from '@/components/playlist/playlist'

// const transform = prefixStyle('transform')

export default {
  mixins: [playerMixin],
  data () {
    return {
      // 音乐地址
      url: '',
      songReady: false,
      // 当前播放时间
      currentTime: 0,
      // 歌曲时长
      duration: 0,
      // 小圆圈进度条周长
      radius: 32,
      // 歌词
      currentLyric: null,
      // 歌词高亮
      currentLineNum: 0
    }
  },
  computed: {
    // 播放样式
    playIcon () {
      return this.playing ? 'icon-bofang iconfont' : 'icon-bofang1 iconfont'
    },
    // 列表样式
    miniIcon () {
      return this.playing ? 'icon-zanting iconfont' : 'icon-bofang2 iconfont'
    },
    // CD图片旋转样式
    cdCls () {
      return this.playing ? 'play' : 'play pause'
    },
    disableCls () {
      return this.songReady ? '' : 'disable'
    },
    // 播放时间跟总时间百分比
    percent () {
      return this.currentTime / this.duration
    },
    // 播放模式
    // iconMode () {
    //   return this.mode === playMode.sequence ? 'iconfont icon-xunhuan2' : this.mode === playMode.loop ? 'iconfont icon-xunhuan1' : 'iconfont icon-xunhuan'
    // },
    ...mapGetters([
      'fullScreen',
      // 'playlist',
      // 'currentSong',
      'playing',
      'currentIndex'
      // 'mode',
      // 'sequenceList'
    ])
  },
  created () {
    console.log(this.currentSong)
    // getSong(33894312).then((res) => {
    //   console.log(res)
    // })
  },
  methods: {
    back () {
      this.setFullScreen(false)
    },
    open () {
      this.setFullScreen(true)
    },
    enter (el, done) {
      const { x, y, scale } = this._getPosAndScale()
      const animation = {
        0: {
          transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
        },
        60: {
          transform: 'translate3d(0, 0, 0) scale(1.1)'
        },
        100: {
          transform: 'translate3d(0, 0, 0) scale(1)'
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter () {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave (el, done) {
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const { x, y, scale } = this._getPosAndScale()
      this.$refs.cdWrapper.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave () {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style.transform = ''
    },
    // 计算大小图片的中心位置差
    _getPosAndScale () {
      var targetWidth = 40
      var paddingLeft = 20
      var paddingBottom = 30
      var paddingTop = 133.5
      var width = window.innerWidth * 0.8
      var scale = targetWidth / width
      var x = -(window.innerWidth / 2 - paddingLeft)
      var y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return {
        x,
        y,
        scale
      }
    },
    // 获取音乐
    _getSong (id) {
      getSong(id).then((res) => {
        this.url = res.data.data[0].url
        console.log(res)
      })
    },
    // 获取歌词
    _getLyric (id) {
      getLyric(id).then((res) => {
        this.currentLyric = new Lyric(res.data.lrc.lyric, this.handleLyric)
        console.log(this.currentLyric)
        if (this.playing) {
          this.currentLyric.play()
        }
      }).catch(() => {
        this.currentLyric = null
        this.currentLineNum = 0
      })
    },
    handleLyric ({ lineNum, txt }) {
      this.currentLineNum = lineNum
      if (lineNum > 5) {
        var lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
    },
    // 歌曲播放完后
    end () {
      if (this.mode === playMode.loop) {
        this.loop()
      } else {
        this.next()
      }
    },
    // 单曲循环
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      // 歌曲播放完重新播放时歌词滚动位置刷新到起始位置
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    // 音乐播放
    togglePlaying () {
      this.setPlayingState(!this.playing)
      // 歌曲播放暂停时歌词不继续滚动
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    // 上一首
    prev () {
      if (!this.songReady) {
        return
      }
      // 当只有一首歌时
      if (this.playlist.length === 1) {
        this.loop()
      } else {
        var index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }
        this.setCurrentIndex(index)
        // playing状态也要改变
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    // 下一首
    next () {
      if (!this.songReady) {
        return
      }
      console.log(this.playlist)
      // 当只有一首歌时
      if (this.playlist.length === 1) {
        console.log(0)
        this.loop()
      } else {
        console.log('01')
        var index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    ready () {
      this.songReady = true
    },
    // 歌曲发送错误触发
    error () {
      this.songReady = true
    },
    updateTime (e) {
      this.currentTime = e.target.currentTime
    },
    // 转化时间方法
    format (interval) {
      interval = interval | 0
      const minute = interval / 60 | 0
      const second = this._pad(interval % 60)
      return `${minute}:${second}`
    },
    _pad (num, n = 2) {
      var len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    // 选择播放模式
    changeMode () {
      const mode = (this.mode + 1) % 3
      this.setPlayMode(mode)
      var list = null
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlaylist(list)
    },
    resetCurrentIndex (list) {
      var index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
      console.log(index)
    },
    // 拖动进度条结束事件(通过子组件传来)
    onProgressBarChange (percent) {
      const currentTime = this.duration * percent
      this.$refs.audio.currentTime = this.duration * percent
      if (!this.playing) {
        this.togglePlaying()
      }
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    // 控制playlist组件显示
    showPlaylist () {
      // console.log(9)
      this.$refs.playlist.show()
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN'
      // setPlayingState: 'SET_PLAYING_STATE',
      // setCurrentIndex: 'SET_CURRENT_INDEX',
      // setPlayMode: 'SET_PLAY_MODE',
      // setPlaylist: 'SET_PLAYLIST'
    })
  },
  watch: {
    currentSong (newVal, oldVal) {
      console.log(newVal)
      if (!newVal) {
        return
      }
      this._getSong(newVal.id)
      if (this.currentLyric) {
        this.currentLyric.stop()
      }
    },
    url (newUrl) {
      this._getLyric(this.currentSong.id)
      this.$refs.audio.src = newUrl
      var stop = setInterval(() => {
        this.duration = this.$refs.audio.duration
        if (this.duration) {
          clearInterval(stop)
        }
      }, 150)
      this.setPlayingState(true)
    },
    // 音乐是否播放
    playing (newPlaying) {
      const audio = this.$refs.audio
      newPlaying ? audio.play() : audio.pause()
    }
  },
  components: {
    ProgressBar,
    ProgressCircle,
    Scroll,
    PlayList
  }
}
</script>

<style lang="less" scoped>
@import '~@/common/stylus/variable';
@import '~@/common/stylus/mixin';

.player {
  .normal-player {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 1000;
    background: @color-background;
    .background {
      position: absolute;
      left: -50%;
      top: -50%;
      width: 300%;
      height: 300%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(30px);
    }
    .top {
      position: relative;
      margin-bottom: 25px;
      .back {
        position: absolute;
        top: 0;
        left: 6px;
        z-index: 50;
        .mui-xiangxia {
          display: block;
          padding: 5px 9px;
          font-size: 35px;
          color: blue;
        }
      }
      .title {
        width: 70%;
        margin: 0 auto;
        padding-top: 10px;
        line-height: 20px;
        text-align: center;
        @include no-wrap();
        font-size: @font-size-large;
        font-weight: bold;
        color: @color-text-l;
      }
      .subtitle {
        width: 70%;
        margin: 0 auto;
        margin-top: 5px;
        line-height: 20px;
        text-align: center;
        @include no-wrap();
        font-size: @font-size-small-x;
        color: @color-text-l;
      }
    }
    .middle {
      display: flex;
      align-items: center;
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;
      font-size: 0;
      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;
        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;
          .cd {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 15px solid rgba(40, 41, 35, 0.1);
            border-radius: 50%;
            &.play {
              animation: rotate 20s linear infinite;
            }
            &.pause {
              animation-play-state: paused;
            }
            .image {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
        }
      }
      .middle-r {
        display: inline-block;
        position: absolute;
        top: 0;
        vertical-align: top;
        width: 100%;
        height: 100%;
        overflow: hidden;
        &.middleR-enter-active, &.middleR-leave-active {
          transition: all 0.2s;
        }
        &.middleR-enter, &.middleR-leave-to {
          opacity: 0;
        }
        .lyric-wrapper {
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;
          .text {
            line-height: 40px;
            color: @color-text-ggg;
            font-size: @font-size-medium;
            &.current {
              color: #FFF;
            }
          }
          .no-lyric {
            line-height: 40px;
            margin-top: 60%;
            color: @color-text-ggg;
            font-size: @font-size-medium;
          }
        }
      }
    }
    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;
      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 80%;
        margin: 0px auto;
        padding: 10px 0;
        .time {
          color: @color-text-l;
          font-size: @font-size-small;
          flex: 0 0 30px;
          line-height: 30px;
          width: 30px;
          &.time-l {
            text-align: left;
          }
          &.time-r {
            text-align: right;
            color: @color-text-gg;
          }
        }
        .progress-bar-wrapper {
          flex: 1;
        }
      }
      .operators {
        display: flex;
        align-items: center;
        .icon {
          flex: 1;
          color: red;
          &.disable {
            color: @color-theme;
          }
          i {
            font-size: 30px;
          }
          .mode {
            font-size: 25px;
          }
          &.i-left {
            text-align: right;
          }
          &.i-center {
            padding: 0 20px;
            text-align: center;
            i {
              font-size: 40px;
            }
          }
          &.i-right {
            text-align: left;
          }
          .icon-like {
            color: @color-sub-theme;
          }
        }
      }
    }
    &.normal-enter-active, &.normal-leave-active {
      transition: all 0.4s;
      .top, .bottom {
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
      }
    }
    &.normal-enter, &.normal-leave-to {
      opacity: 0;
      .top {
        transform: translate3d(0, -100px, 0);
      }
      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }
  .mini-player {
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 1001;
    width: 100%;
    height: 60px;
    background: rgba(255, 255, 255, 0.85);
    &.mini-enter-active, &.mini-leave-active {
      transition: all 0.4s
    }
    &.mini-enter, &.mini-leave-to {
      opacity: 0
    }
    .icon {
      flex: 0 0 40px;
      /*width: 40px;*/
      padding: 0 10px 0 20px;
      img {
        border-radius: 50%;
        &.play {
          animation: rotate 10s linear infinite;
        }
        &.pause {
          animation-play-state: paused;
        }
      }
    }
    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      overflow: hidden;
      .name {
       margin-bottom: 2px;
       line-height: 14px;
       @include no-wrap();
       font-size: @font-size-medium;
       color: @color-text;
      }
      .desc {
       @include no-wrap();
        font-size: @font-size-small;
        color: @color-text;
      }
    }
    .control {
      flex: 0 0 30px;
      /*width: 30px;*/
      padding: 0 10px;
      .icon-setting {
        font-size: 30px;
        color: @color-theme-d;
      }
      .iconfont {
        position: relative;
        left: -5px;
        top: -3px;
      }
      .icon-mini {
        position: absolute;
        font-size: 32px;
        left: 0;
        top: 6.5px;
      }
      .fa-play {
        color: @color-theme-d;
        font-size: 14px;
        position: absolute;
        left: 12px;
        top: 8.5px;
      }
      .fa-stop {
        color: @color-theme-d;
        font-size: 12px;
        position: absolute;
        left: 11px;
        top: 10px;
      }
    }
  }
}
@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
